package drrr.controller;

import com.opensymphony.xwork2.ActionContext;
import drrr.orm.RoomEntity;
import drrr.orm.RoomMemberEntity;
import drrr.orm.UserEntity;
import org.apache.struts2.ServletActionContext;
import org.hibernate.exception.ConstraintViolationException;

import java.util.Map;

/**
 * Created by lirance on 15/5/21.
 * 进入房间
 */
public class EnterRoomAction extends BaseAction {

    private String id;

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    @Override
    public String execute() throws Exception {

        int roomid = Integer.parseInt(id);
        RoomEntity roomEntity = getAllService().getRoomService().find(roomid);
        Map<String, Object> session = ServletActionContext.getContext().getSession();
        session.put("room", roomEntity);

        //进入房间时写入数据库.
        UserEntity userEntity = ((UserEntity) session.get("user"));
        if (userEntity != null) {
            int memberid = userEntity.getId();
            RoomMemberEntity roomMemberEntity = new RoomMemberEntity();
            roomMemberEntity.setRoomId(roomid);
            roomMemberEntity.setMemberId(memberid);
            try {
                getAllService().getRoomMemberService().insert(roomMemberEntity);
            }catch (ConstraintViolationException e)
            {
                e.printStackTrace();
            }
            //得到在线人数
            String roomOnline=String.format("roomOnline%s", roomid + "");
            int onlineNum;
           try {
               onlineNum = (int) ActionContext.getContext().getApplication().get(roomOnline);
           }catch (Exception e){
               onlineNum = 0;
               ActionContext.getContext().getApplication().put(roomOnline,1);
           }

            int membernum = roomEntity.getMembernum();
            if (onlineNum < membernum) {
                ActionContext.getContext().getApplication().put(roomOnline,onlineNum+1);
                session.put("member", roomMemberEntity);
                return SUCCESS;
            } else return ERROR;
        }
    else {
            return LOGIN;
        }


    }
}
